/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: DIBasePicActivity.java
 * @Package com.jiyi.activity.datainput
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2018-1-11 上午9:44:17
 * @version V1.0
 */
package com.jiyi.activity.datainput;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jiyi.bean.MulGridViewBean;
import com.jiyi.bean.SingleImageBean;
import com.jiyi.inteface.DownloadPicOverInterface;
import com.jiyi.inteface.PickPopInterface;
import com.jiyi.view.PickPopView;
import com.jiyi.widget.picselect.PicFloderList_Activity;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.jiyi.widget.picshow.ImagePagerActivity;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.PermissionUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @ClassName: DIBaseMorePicActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2018-1-11 上午9:44:17
 */
public class DIBaseMorePicActivity extends ActivityBase implements PickPopInterface {
    private int max = 4;
    private InputMethodManager imm;
    PickPopView mPickPopView;
    // 图片路径
    private Uri mCameraUri;
    // 拍摄事件
    public final int CAMARE_CODE = 1;
    // 从相册选择事件
    public final int CHOOSE_PICTURE = 2;
    // 图片路径
    private String filePath;
    // 加载的进度条
    Dialog dialog;
    Map<Integer, Map<Integer, String>> results = new HashMap<Integer, Map<Integer, String>>();

    DownloadPicOverInterface downloadPicOverInterface;

    //当前操作的Gridview
    int currentOperate = 0;
    protected  MulGridViewBean mulGridViewBean = new MulGridViewBean();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDIBase();
    }

    @Override
    protected void onDestroy() {
        hideDialog(dialog);
        PicSelectConstans.current.clear();
        PicSelectConstans.publish_pics.clear();
        super.onDestroy();
    }

    public void initDIBase() {
        imm = DeviceUtil.getInstance().getImm();
        mPickPopView = new PickPopView(this, this);
    }

    @Override
    public void OnShootListener() {
        if (PermissionUtil.checkPermission(this, PermissionUtil.CARAME)) {
            useCamere();
        }

    }

    @Override
    public void OnAlbumListener() {
        // 添加图片 从相册
        PicSelectConstans.headUrl = "";
        Intent intent = new Intent(this, PicFloderList_Activity.class);
        intent.putExtra("max", max);
        startActivityForResult(intent, CHOOSE_PICTURE);
        mPickPopView.hidePopWindow();
    }

    /**
     * <p>
     * Title: OnCancleListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see PickPopInterface#OnCancleListener()
     */
    @Override
    public void OnCancleListener() {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: OnShowListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see PickPopInterface#OnShowListener()
     */
    @Override
    public void OnShowListener() {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: OnHideListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see PickPopInterface#OnHideListener()
     */
    @Override
    public void OnHideListener() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMARE_CODE && resultCode == RESULT_OK) {
            if (!TextUtils.isEmpty(filePath)) {
                mulGridViewBean.getSingleImageList().get(currentOperate).getImageList().add(filePath);
                refreshAdapter(mulGridViewBean.getSingleImageList().get(currentOperate));
            }
        } else if (requestCode == CHOOSE_PICTURE) {
            mulGridViewBean.getSingleImageList().get(currentOperate).getImageList().clear();
            if (PicSelectConstans.publish_pics.size() > 0) {
                mulGridViewBean.getSingleImageList().get(currentOperate).getImageList().addAll(PicSelectConstans.publish_pics);
            }
            refreshAdapter(mulGridViewBean.getSingleImageList().get(currentOperate));
        }
    }

    @Override
    public void onBackPressed() {
        PicSelectConstans.current.clear();
        PicSelectConstans.publish_pics.clear();
        super.onBackPressed();
    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final int parentPosition;
        private final int childPosition;

        public getImageCacheAsyncTask(int parentPosition, int childPosition) {
            this.parentPosition = parentPosition;
            this.childPosition = childPosition;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl = params[0];
            try {
                return Glide
                        .with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL,
                                Target.SIZE_ORIGINAL).get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            // 此path就是对应文件的缓存路径
            String path = result.getPath();
            Log.e("path", path);
            mulGridViewBean.getSingleImageList().get(parentPosition).getImageList().set(childPosition, path);
            Map<Integer, String> childResults = new HashMap<Integer, String>();
            childResults.put(childPosition, "2");
            results.put(parentPosition, childResults);
            if (isDownLoadSuccess()) {
                // 图片数组
                int size = mulGridViewBean.getSingleImageList().size();

                for (int i = 0; i < size; i++) {
                    for (int j = 0; j < mulGridViewBean.getSingleImageList().get(i).getImageList().size(); j++) {
                        if (mulGridViewBean.getSingleImageList().get(i).getImageList().get(j).contains("http")) {
                            Log.e("ttt     ", mulGridViewBean.getSingleImageList().get(i).getImageList().get(j) + "\n");
                        }
                    }
                }
                // doPostPics();
                if (downloadPicOverInterface != null) {
                    hideDialog(dialog);
                    downloadPicOverInterface.post();
                }
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

    class MyAdapter extends BaseAdapter {
        SingleImageBean singleImageBean;

        public MyAdapter(SingleImageBean singleImageBean) {
            this.singleImageBean = singleImageBean;
        }

        @Override
        public int getCount() {
//            if (singleImageBean.getImageList().size() > 0) {
//                return singleImageBean.getImageList().size() + 2;
//            }

            if (singleImageBean.getImageList().size() > 0) {
                return singleImageBean.getImageList().size() + 1;
            }
            return 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        public SingleImageBean getSingleImageBean() {
            return singleImageBean;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = getLayoutInflater().inflate(
                    R.layout.simple_imageview, null);
            ImageView iv_simple = (ImageView) inflate
                    .findViewById(R.id.iv_simple);
            ImageView iv_delpic = (ImageView) inflate
                    .findViewById(R.id.iv_delpic);

            if (singleImageBean.getImageList().size() <= 0) {
                iv_simple.setImageDrawable(getResources().getDrawable(
                        R.mipmap.add_square));
            }
            else {
                iv_simple.setImageDrawable(getResources().getDrawable(
                            R.mipmap.add_square));
                if (position != singleImageBean.getImageList().size() && position != singleImageBean.getImageList().size() + 1) {
                    String sourcePath = singleImageBean.getImageList().get(position);
                    GlideUtil.load(AppBase.Context, sourcePath, iv_simple);
                }

//                if (position == singleImageBean.getImageList().size()) {
//                    iv_simple.setImageDrawable(getResources().getDrawable(
//                            R.mipmap.add_square));
//                } else if (position == singleImageBean.getImageList().size() + 1) {
//                    iv_simple.setImageDrawable(getResources().getDrawable(
//                            R.mipmap.delpic));
//                }
//                else {
//                    if (singleImageBean.getDelModel()) {
//                        iv_delpic.setVisibility(View.VISIBLE);
//                    } else {
//                        iv_delpic.setVisibility(View.GONE);
//                    }
//
//                    String sourcePath = singleImageBean.getImageList().get(position);
//                    GlideUtil.load(AppBase.Context, sourcePath, iv_simple);
//
//                }
            }
            return inflate;
        }
    }

    protected void refreshAdapter() {
        for (SingleImageBean singleImageBean : mulGridViewBean.getSingleImageList()) {
            refreshAdapter(singleImageBean);
        }

    }

    protected void refreshAdapter(final SingleImageBean singleImageBean) {
        if (singleImageBean.getImageList().size() <= 0) {
            singleImageBean.setDelModel(false);
        }

        if (singleImageBean.getBaseAdapter() == null) {
            MyAdapter adapter = new MyAdapter(singleImageBean);
            singleImageBean.setBaseAdapter(adapter);


            float density = DeviceUtil.getInstance().getBiLi(); // 像素密度
            int screenWidth = DeviceUtil.getInstance().getScreenWidth();
            // 15是父节点的padding 2是左右两边
            screenWidth -= 15 * 2 * density;
            // 求出最大可放的图片个数 60是item的宽度 10是item之间的间距
            int maxNum = (int) Math.floor(screenWidth / ((60 + 10) * density));
            Log.e("maxNum ", maxNum + "");
            singleImageBean.getGridView().setNumColumns(maxNum);
            singleImageBean.getGridView().setAdapter(adapter);
            singleImageBean.getGridView().setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View view,
                                        int position, long arg3) {
                    if (singleImageBean.getDelModel()) {
                        if (singleImageBean.getImageList().size() > 0) {

                            if (position == singleImageBean.getImageList().size()) {
                                addPic(singleImageBean);
                            } else if (position == singleImageBean.getImageList().size() + 1) {
                                singleImageBean.setDelModel(false);
                                refreshAdapter(singleImageBean);
                            } else {
                                singleImageBean.getImageList().remove(position);
                                refreshAdapter(singleImageBean);
                            }
                        }
                    } else {
                        if (singleImageBean.getImageList().size() <= 0) {
                            addPic(singleImageBean);
                        } else {
                            if (singleImageBean.getImageList().size() == position) {
                                addPic(singleImageBean);
                            } else if (singleImageBean.getImageList().size() + 1 == position) {
                                singleImageBean.setDelModel(true);
                                refreshAdapter(singleImageBean);
                            } else {
                                String[] urls = new String[singleImageBean.getImageList().size()];
                                for (int i = 0, n = singleImageBean.getImageList().size(); i < n; i++) {
                                    urls[i] = singleImageBean.getImageList().get(i);
                                }

                                Intent intent = new Intent(view.getContext(),
                                        ImagePagerActivity.class);
                                intent.putExtra(
                                        ImagePagerActivity.EXTRA_IMAGE_URLS,
                                        urls);
                                intent.putExtra(
                                        ImagePagerActivity.EXTRA_IMAGE_INDEX,
                                        position);
                                startActivity(intent);
                            }
                        }
                    }
                }
            });
        } else {
            singleImageBean.getBaseAdapter().notifyDataSetChanged();
        }
    }

    private void addPic(SingleImageBean singleImageBean) {
        if (singleImageBean.getImageList().size() >= max) {
            ToastUtil.getInstances().showMsg("最多只能添加" + max + "张图片");
            return;
        }
        PicSelectConstans.pic_tag = 2;
        singleImageBean.setDelModel(false);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(singleImageBean.getGridView().getWindowToken(), 0); // 强制隐藏键盘
        }
        PicSelectConstans.current.clear();
        if (singleImageBean.getImageList().size() > 0) {
            PicSelectConstans.current.addAll(singleImageBean.getImageList());
        }
        mPickPopView.showPopWindow();
        currentOperate = singleImageBean.getPosition();
    }

    /**
     * @author: HYM
     * @Title: downloadImage
     * @Description: TODO(保存前重新下载线上的图片) void
     * @date: 2018-1-11
     */
    protected void downloadImage() {

        dialog = showDialog(dialog,"图片存储中...");
        // 清空任务记录
        results.clear();
        // 根据是否需要下载图片来处理保存
        boolean needDownload = false;
        // 图片数组
        int size = mulGridViewBean.getSingleImageList().size();

//        Observable.fromArray(mulGridViewBean.getSingleImageList())
//                .flatMap(new Function<List<SingleImageBean>, ObservableSource<String>>() {
//                    @Override
//                    public ObservableSource<String> apply(List<SingleImageBean> singleImageBeans) throws Exception {
//
//                        return null;
//                    }
//                }).subscribe(new SampleProgressObserver<String>(this) {
//            @Override
//            public void onNext(String path) {
//                super.onNext(path);
//            }
//        });

        for (int i = 0; i < mulGridViewBean.getSingleImageList().size(); i++) {
            for (int j = 0; j < mulGridViewBean.getSingleImageList().get(i).getImageList().size(); j++) {
                if (mulGridViewBean.getSingleImageList().get(i).getImageList().get(j).contains("http")) {
                    needDownload = true;
                    Map<Integer, String> childResults = new HashMap<Integer, String>();
                    childResults.put(j, "1");
                    results.put(i, childResults);
                    new getImageCacheAsyncTask(i, j)
                            .execute(mulGridViewBean.getSingleImageList().get(i).getImageList().get(j));
                }
            }
        }

        if (!needDownload) {
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < mulGridViewBean.getSingleImageList().get(i).getImageList().size(); j++) {
                    if (mulGridViewBean.getSingleImageList().get(i).getImageList().get(j).contains("http")) {
                        Log.e("ttt     ", mulGridViewBean.getSingleImageList().get(i).getImageList().get(j) + "\n");
                    }
                }
            }


            // doPostPics();
            if (downloadPicOverInterface != null) {
                hideDialog(dialog);
                downloadPicOverInterface.post();
            }
        }

    }

    boolean isDownLoadSuccess()

    {
        for (Integer i : results.keySet()) {
            for (Integer j : results.get(i).keySet())
                if (results.get(i).get(j).equals("1")) {
                    return false;
                }
        }
        return true;
    }

    protected DownloadPicOverInterface getDownloadPicOverInterface() {
        return downloadPicOverInterface;
    }

    protected void setDownloadPicOverInterface(
            DownloadPicOverInterface downloadPicOverInterface) {
        this.downloadPicOverInterface = downloadPicOverInterface;
    }

    private void useCamere() {
        File fileDir = new File(AppConfig.DIR_IMAGE);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        filePath = AppConfig.DIR_IMAGE + "temp" + new Date().getTime() + ".jpg";
        File file = new File(filePath);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mCameraUri = FileProvider.getUriForFile(this, "com.swift.maintenance.updateprovider", file);
        } else {
            mCameraUri = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
            filePath = mCameraUri.getPath();
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");


        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri);
        startActivityForResult(intent, CAMARE_CODE);
        mPickPopView.hidePopWindow();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtil.CARAME) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                useCamere();
            } else {
                ToastUtil.getInstances().showMsg("无法访问相机");
            }
        }
    }

    protected MultipartBody.Builder putBody(MultipartBody.Builder source, String filed, MediaType mediaType, Object value) {
        if (value instanceof String) {
            source.addFormDataPart(filed, value.toString());
        } else if (value instanceof File) {
            File file = (File) value;
            source.addFormDataPart(filed, new Date().getTime()+".jpg", RequestBody.create(mediaType, file));
        }
        return source;
    }
}
